'use client'

import { useRouter, useSearchParams } from 'next/navigation'
import { useEffect, useState } from 'react'
import { supabase } from '@/lib/supabase-client'
import type { Category } from '@/types'

export function CategoryFilter() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const [categories, setCategories] = useState<Category[]>([])
  const [selectedCategory, setSelectedCategory] = useState(searchParams.get('category') || '')

  useEffect(() => {
    const fetchCategories = async () => {
      try {
        const response = await fetch('/api/categories')
        const result = await response.json()

        if (response.ok && result.success) {
          setCategories(result.data || [])
        } else {
          // 如果API失败，使用静态数据作为后备
          setCategories([
            { id: '1', name: '开发工具', description: '', icon: '💻', createdAt: new Date(), updatedAt: new Date() },
            { id: '2', name: '设计工具', description: '', icon: '🎨', createdAt: new Date(), updatedAt: new Date() },
            { id: '3', name: '效率工具', description: '', icon: '⚡', createdAt: new Date(), updatedAt: new Date() },
            { id: '4', name: '娱乐游戏', description: '', icon: '🎮', createdAt: new Date(), updatedAt: new Date() },
          ])
        }
      } catch (error) {
        console.error('获取分类失败:', error)
        // 使用静态数据作为后备
        setCategories([
          { id: '1', name: '开发工具', description: '', icon: '💻', createdAt: new Date(), updatedAt: new Date() },
          { id: '2', name: '设计工具', description: '', icon: '🎨', createdAt: new Date(), updatedAt: new Date() },
          { id: '3', name: '效率工具', description: '', icon: '⚡', createdAt: new Date(), updatedAt: new Date() },
          { id: '4', name: '娱乐游戏', description: '', icon: '🎮', createdAt: new Date(), updatedAt: new Date() },
        ])
      }
    }

    fetchCategories()
  }, [])

  const handleCategoryChange = (categoryId: string) => {
    const params = new URLSearchParams(searchParams)
    
    if (categoryId) {
      params.set('category', categoryId)
    } else {
      params.delete('category')
    }
    
    setSelectedCategory(categoryId)
    router.push(`/?${params.toString()}`)
  }

  return (
    <div className="flex items-center gap-2">
      <label htmlFor="category" className="text-sm font-medium text-gray-700">
        分类:
      </label>
      <select
        id="category"
        value={selectedCategory}
        onChange={(e) => handleCategoryChange(e.target.value)}
        className="border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"
      >
        <option value="">全部分类</option>
        {categories.map((category) => (
          <option key={category.id} value={category.id}>
            {category.icon} {category.name}
          </option>
        ))}
      </select>
    </div>
  )
}
